package com.carbohydrate42.kotlin_compose_demo.compose

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.app.ActivityCompat

/**
 * 获取位置信息
 *
 * 一般有好几种方式, GPS 比较耗电, WIFI 基站定位 等几种方式又不大稳定
 * 后台获取位置信息和前台获取位置信息的权限还有点不一样
 *
 * https://juejin.cn/post/7049900644383064078
 */
@SuppressLint("MissingPermission")
@Preview(showSystemUi = true, showBackground = true)
@Composable
fun TryFetchLocation() {
    val context = LocalContext.current

    var locationStr by remember {
        mutableStateOf("no info")
    }

    var allGranted by remember {
        mutableStateOf(false)
    }

    // 动态请求一下 WRITE_EXTERNAL_STORAGE 权限
    val requestPermission =
        rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { isGrantedList ->
            var isAllGranted = true
            for (isGrantedEntry in isGrantedList) {
                if (!isGrantedEntry.value) {
                    isAllGranted = false
                    Log.i("Permission: ", "${isGrantedEntry.key} Denied")
                } else {
                    Log.i("Permission: ", "${isGrantedEntry.key} Granted")
                }
            }
            allGranted = isAllGranted
        }

    LaunchedEffect(Unit) {
        requestPermission.launch(
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        )
    }

    if (!allGranted) {
        Text(text = "permission denied")
    } else {
        val locManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val loc = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)

        locationStr = loc?.toString() ?: ""

        locManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            0,
            0F
        ) { location ->
            Log.e("gpslocation", location.toString())
            locationStr = location.toString()
        }

        Text(text = "location : $locationStr")
    }


}
